from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages

from .models import Score
from .forms import ScoreForm


@login_required
def score_list(request):
	from django.core.paginator import Paginator
	qs = Score.objects.select_related('student', 'grade').all()
	paginator = Paginator(qs, 12)
	page = request.GET.get('page')
	scores = paginator.get_page(page)
	return render(request, 'scores/score_list.html', {'scores': scores})


@login_required
def score_detail(request, pk):
	score = get_object_or_404(Score, pk=pk)
	return render(request, 'scores/score_detail.html', {'score': score})


@login_required
def score_add(request):
	if request.method == 'POST':
		form = ScoreForm(request.POST)
		if form.is_valid():
			form.save()
			messages.success(request, '成绩已添加')
			return redirect('scores:score_list')
	else:
		form = ScoreForm()
	return render(request, 'scores/score_form.html', {'form': form, 'title': '添加成绩'})


@login_required
def score_edit(request, pk):
	score = get_object_or_404(Score, pk=pk)
	if request.method == 'POST':
		form = ScoreForm(request.POST, instance=score)
		if form.is_valid():
			form.save()
			messages.success(request, '成绩已更新')
			return redirect('scores:score_detail', pk=pk)
	else:
		form = ScoreForm(instance=score)
	return render(request, 'scores/score_form.html', {'form': form, 'title': f'编辑成绩 - {score.student.name}'})


@login_required
def score_delete(request, pk):
	score = get_object_or_404(Score, pk=pk)
	if request.method == 'POST':
		score.delete()
		messages.success(request, '成绩已删除')
		return redirect('scores:score_list')
	return redirect('scores:score_detail', pk=pk)
